﻿using System.Web.Providers.Entities;
using Microsoft.Ajax.Utilities;
using Microsoft.SqlServer.Server;
using sourcephi.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Data.Objects;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Data.Entity.Infrastructure;
using System.IO;
using System.Text;
using Webdiyer.WebControls.Mvc;
using System.Net;
namespace sourcephi.Controllers
{
    public class DafenController : Controller
    {
        //
        // GET: /Dafen/
        public static Func<Object, string> isLogin = sesssion => sesssion as string ?? string.Empty;
        public string loginn;
        public static string upload, upload2;
        //public string upload, upload2;
        private Models.sourceEntities db = new Models.sourceEntities();

        public DafenController()
        {
            db.Configuration.ValidateOnSaveEnabled = false;
        }

        public ActionResult Gcszlsc()
        {
          return View();
        }

        public ActionResult Updgcs()
        {
            if(string.IsNullOrEmpty(isLogin(Session["loginname"])))
            {
                return RedirectToAction("Index", "Login");//
            }
            loginn = Session["loginname"].ToString();
            List<SelectListItem> deptList=new List<SelectListItem>();
            deptList.Add(new SelectListItem { Text = "技术业务室", Value = "技术业务室" });
            deptList.Add(new SelectListItem { Text = "安全管理室", Value = "安全管理室" });
            deptList.Add(new SelectListItem { Text = "区管网络通信室", Value = "区管网络通信室" });
            deptList.Add(new SelectListItem { Text = "终端网络通信室", Value = "终端网络通信室" });
            deptList.Add(new SelectListItem { Text = "有线通信室", Value = "有线通信室" });
            deptList.Add(new SelectListItem { Text = "计算机应用开发室", Value = "计算机应用开发室" });
            deptList.Add(new SelectListItem { Text = "办公自动化设备室", Value = "办公自动化设备室" });
            deptList.Add(new SelectListItem { Text = "集群通信室", Value = "集群通信室" });
            ViewBag.deptlist = deptList;

            List<SelectListItem> zhichengList = new List<SelectListItem>();
            zhichengList.Add(new SelectListItem { Text = "主任工程师", Value = "主任工程师" });
            zhichengList.Add(new SelectListItem { Text = "工程师", Value = "工程师" });
            zhichengList.Add(new SelectListItem { Text = "助理工程师", Value = "助理工程师" });
            zhichengList.Add(new SelectListItem { Text = "技术员", Value = "技术员" });
            ViewBag.zhichengList = zhichengList;

            
            return View();
        }

        [HttpPost]
        public ActionResult Updgcs(string 所在部门, string 技术职称)
        {
            string returnUrl = "/";
            if (upload != "" && upload2 != "")//Session["upload"]!="" && Session["upload2"]!=""
            {
                string fileNameZj = upload;   //Session["upload"].ToString();
                string fileNameZZ = upload2; //Session["upload2"].ToString();
                string loginname = Session["loginname"].ToString();
                //var fileName = Path.Combine(Request.MapPath("~/UploadFiles"), Path.GetFileName(file.FileName));
                try
                {
                    //   return Content("上传成功！", "text/plain");
                    if (ModelState.IsValid)
                    {
                        var dafens = new dafen { loginname = loginname, 所在部门 = 所在部门, 技术职称 = 技术职称, 履行职责 = fileNameZZ, 工程师总结 = fileNameZj, addtime = DateTime.Now };
                        db.dafen.Add(dafens);
                        db.SaveChanges();
                        //   return RedirectToAction("Index", "UploadText", "上传并保存成功");
                        //   return Content("上传并保存成功！", "text/plain");
                    }
                }
                catch
                {
                    return Content("上传异常 ！", "text/plain");
                }
                var script = String.Format("<script>alert('上传成功!');location.href='{0}'</script>", Url.Action("Index", "Home"));
                return Content(script, "text/html");
            }
            else
            {
                
                var script = String.Format("<script>alert('文件未上传，请上传后提交！');location.href='{0}'</script>", Url.Action("Updgcs"));
                return Content(script, "text/html");
            }
            //return Redirect(returnUrl);
        }

        public ActionResult Upload2(HttpPostedFileBase Filedata)
        {
            // 如果没有上传文件
            if (Filedata == null ||
                string.IsNullOrEmpty(Filedata.FileName) ||
                Filedata.ContentLength == 0)
            {
                return this.HttpNotFound();
            }
            string dt = DateTime.Now.DayOfYear.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
            // 保存到 ~/photos 文件夹中，名称不变
            string filename = System.IO.Path.GetFileName(Filedata.FileName);
            string virtualPath =
                string.Format("~/uploadfile/{0}", dt + filename);
            // 文件系统不能使用虚拟路径
            //string vp = virtualPath.Replace("/", @"\");
            string path = this.Server.MapPath(virtualPath);
            TempData["strpath"] = path;
            Filedata.SaveAs(path);
            Session["upload2"] = virtualPath;
            upload2 = virtualPath;//Session["upload2"] = virtualPath;
            return this.Json(new { });
        }

        public ActionResult Upload(HttpPostedFileBase Filedata)
        {
            // 如果没有上传文件
            if (Filedata == null ||
                string.IsNullOrEmpty(Filedata.FileName) ||
                Filedata.ContentLength == 0)
            {
                return this.HttpNotFound();
            }
            string dt = DateTime.Now.DayOfYear.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
            // 保存到 ~/photos 文件夹中，名称不变
            string filename = System.IO.Path.GetFileName(Filedata.FileName);
            string virtualPath =
                string.Format("~/uploadfile/{0}", dt+ filename);
            // 文件系统不能使用虚拟路径
            //string vp = virtualPath.Replace("/", @"\");
            string path = this.Server.MapPath(virtualPath);
            TempData["strpath"] = path;
            Filedata.SaveAs(path);
            //test set cookie
            //TempData["upload"] = virtualPath;
            Session["upload"] = virtualPath;
            upload = virtualPath;//Session["upload"] = virtualPath;
            return this.Json(new { });
        }

        public ActionResult Qzdf()
        {
            int dfid = int.Parse(Request.QueryString["dfid"]);
            TempData["dfid"] = dfid;
            var dfry = (from p in db.dafen
                           where p.nid == dfid
                           select p).FirstOrDefault();
            if (dfry != null)
            {
                return View(dfry);
            }
            return View();
        }

        //[HttpPost]
        //public ActionResult Qzdf(string val)
        //{
        //    return View();
        //}
        [HttpPost]
        public ActionResult MyAjax(Models.dafen model,string val)
        {
            string host = Dns.GetHostName();
            bool wrong = true;
            //string vals = Request["val"].ToString();
            TempData["Values"] = val;
            var dfid = int.Parse(TempData["dfid"].ToString());
            dafen dafensDafen = (from df in db.dafen where df.nid == dfid select df).FirstOrDefault();
            try
            {
                if (dafensDafen.群众打分 != null)
                {
                    dafensDafen.群众打分 += "," + val;
                    dafensDafen.姓名 += "||" + host;
                    db.SaveChanges();
                }
                else
                {
                    dafensDafen.群众打分 += val;
                    dafensDafen.姓名 += "||" + host;
                    db.SaveChanges();
                }

            }
            catch (Exception ex)
            {
                wrong=false;
            }

            return this.Json(wrong);
        }

        public ActionResult Dftongji(int id=1)
        {
            var startTime = new DateTime(DateTime.Now.Date.Year, 1, 1);
            var endTime = new DateTime(DateTime.Now.Date.Year, 12, 31);

            if (string.IsNullOrEmpty(isLogin(Session["dept"])))
            {
                Session["dept"] = "网络中心";
            }
            var dept = Session["dept"].ToString();
            if (dept == "管理员")//管理员
            {
                //分页控件用topagelist
               var dafenlist =
                    db.dafen.Where(p => p.addtime > startTime && p.addtime < endTime)
                        .OrderBy(d => d.addtime).OrderBy(d => d.所在部门)
                        .ToPagedList(id, 8);
                return View(dafenlist);
            }
            else if (dept == "网络中心")//网络中心
            {
                var dafenlist =
                    db.dafen.Where(p => p.addtime > startTime && p.addtime < endTime)
                        .OrderBy(d => d.addtime).OrderBy(d => d.所在部门)
                        .ToPagedList(id, 8);
                return View(dafenlist);
            }
            else //科室
            {
                var dafenlist =
                   db.dafen.Where(p => p.addtime > startTime && p.addtime < endTime && p.所在部门 == dept)
                       .OrderBy(d => d.addtime).OrderBy(d => d.所在部门)
                       .ToPagedList(id, 8);
                return View(dafenlist);
            }
            return View();
        }

        //public ActionResult List(int id)
        //{
        //    Models.dafen dafen = db.dafen.First();
        //    int pageIndex = id;
        //    int pageSize = 5;
        //    int rowCount = db.dafen.Count();
        //    int pageCount = Convert.ToInt16(Math.Ceiling((rowCount*1.0)/pageSize));

        //    var startTime = new DateTime(DateTime.Now.Date.Year, 1, 1);
        //    var endTime = new DateTime(DateTime.Now.Date.Year, 12, 31);  
        //    List<Models.DTO.dafenDTO> dafenlist = (from p in db.dafen
        //                                    where p.addtime>startTime && p.addtime<endTime
        //                   select p).OrderBy(d=>d.addtime).Skip((pageIndex-1)*pageSize).Take(pageSize).ToList().Select(s=>s.ToDto()).ToList();
        //    Models.PagedDataModel<Models.DTO.dafenDTO> dataModel = new Models.PagedDataModel<Models.DTO.dafenDTO>()
        //    {
        //        PagedData = dafenlist,
        //        PageCount = pageCount,
        //        PageIndex = pageIndex,
        //        PageSize = pageSize,
        //        RowCount = rowCount
        //    };
        //    Models.JsonModel jsonModel = new JsonModel()
        //    {
        //        Data = dataModel,
        //        Msg = "成功",
        //        Statu = "ok"
        //    };
        //    return Json(jsonModel, JsonRequestBehavior.AllowGet);
        //}

        public ActionResult DownFile(string filePath, string fileName)
        {
            filePath = Server.MapPath(filePath);
            FileStream fs = new FileStream(filePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.Charset = "UTF-8";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            Response.ContentType = "application/octet-stream";

            Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fileName));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
            return new EmptyResult();
        }

        public ActionResult Pwdf()
        {
            if (string.IsNullOrEmpty(isLogin(Session["loginname"])))
            {
                return RedirectToAction("Index", "Login");//
            }
            int dfid = int.Parse(Request.QueryString["dfid"]);
            TempData["dfid"] = dfid;
            var dfry = (from p in db.dafen
                        where p.nid == dfid
                        select p).FirstOrDefault();
            if (dfry != null)
            {
                return View(dfry);
            }
            return View();
        }
        [HttpPost]
        public ActionResult MyAjax2(Models.dafen model, string val)
        {
            bool wrong = true;
            //string vals = Request["val"].ToString();
            TempData["Values"] = val;
            var dfid = int.Parse(TempData["dfid"].ToString());
            dafen dafensDafen = (from df in db.dafen where df.nid == dfid select df).FirstOrDefault();
            try
            {
                if (dafensDafen.评委打分 != null)
                {
                    dafensDafen.评委打分 += "," + val;
                    dafensDafen.other += " pw:" + Session["loginname"].ToString();
                    db.SaveChanges();
                }
                else
                {
                    dafensDafen.评委打分 += val;
                    dafensDafen.other += " pw:" + Session["loginname"].ToString();
                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                wrong = false;
            }

            return this.Json(wrong);
        }

        public ActionResult Bmdf()
        {
            if (string.IsNullOrEmpty(isLogin(Session["loginname"])))
            {
                return RedirectToAction("Index", "Login");//
            }
            int dfid = int.Parse(Request.QueryString["dfid"]);
            TempData["dfid"] = dfid;
            var dfry = (from p in db.dafen
                        where p.nid == dfid
                        select p).FirstOrDefault();
            if (dfry != null)
            {
                return View(dfry);
            }
            return View();
        }
        [HttpPost]
        public ActionResult MyAjax3(Models.dafen model, string val, string val1, string val2, string val3, string val4, string val5, string val6, string val7, string val8, string val9, string val10, string val11, string val12,string val13,string val14,string val15,string val16,string val17)
        {
            bool wrong = true;
            //string vals = Request["val"].ToString();
            TempData["Values"] = val;
            var dfid = int.Parse(TempData["dfid"].ToString());
            dafen dafensDafen = (from df in db.dafen where df.nid == dfid select df).FirstOrDefault();
            try
            {
                dafensDafen.部门打分 = val;
                dafensDafen.val1 = val1 + "," + val2 + "," + val3 + "," + val4 + "," + val5 + "," + val6 + "," + val7 + "," + val8 + "," + val9 + "," + val10 + "," + val11 + "," + val12 + "," + val13 + "," + val14 + "," + val15 + "," + val16 + "," + val17;
                dafensDafen.other += " bm:" + Session["loginname"].ToString();
                db.SaveChanges();

            }
            catch (Exception ex)
            {
                wrong = false;
            }
            return this.Json(wrong);
        }
        public ActionResult bmdf_ys()
        {
            int nid =int.Parse(Request.QueryString["mid"]);
            var dafenlist =
                    db.dafen.Where(p => p.nid == nid).ToList();
            return View(dafenlist);
        }
    }
}
